package cc.langk.core.db;

import cc.langk.core.util.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * TODO  sql查询分析
 * @author ouyang 创建时间：2012-03-11 08:51:06
 */
public class Query implements Serializable {
	private static final long serialVersionUID = 1L;
    
	static Log log = LogFactory.getLog(Query.class);
	/**
	 * 所有的查询条件
	 */
	List<Condition> coList = new ArrayList<Condition>();
	/**
	 * 查询条件的初始化 调用 init 方法后才赋值
	 */
	Map<String, Object> paramMap = new LinkedHashMap<String, Object>();

	/**
	 * 查询的参数
	 */
	List<Object> paramList = new ArrayList<Object>();
	
	private String rsSqlString=""; //最后拼接完的SQL 语句
	
	private String orderByString="";
	private String groupByString="";

	private boolean init=false;
	/**
	 * TODO   变量所有的特殊条件
	 * 遍历可变条件的时候 去掉为空的字符串 update 03 26
	 */
	public void init() {
		if(coList.size()>0 && !init){ //  初始化(只初始化一次)
			for (Condition co : coList) {
				if (co.getColumnName()!=null && co.getValue()!=null && co.getValue().toString().length()>0){ 
				    paramMap.put(co.getColumnName(), co.getValue());
				}else if(co.getType()!=null && co.getType().name().equals(FindType.IS_NULL.name())){
					paramMap.put(co.getColumnName(), " is null");
				}else if(co.getType()!=null && co.getType().name().equals(FindType.NOT_NULL.name())){
					paramMap.put(co.getColumnName(), " not null");
				}
			}
			rsSqlString  = SqlParse.parseQuery(paramMap, paramList); //  初始化 SQL 语句
			//log.info("★★★★★★★★★★初始化 完成--------------------");
		}
		init = true;
	}
	/**
	 * 存放在 特殊条件处 
	 * TODO  
	 * @author ouyang 创建时间：2012-03-12 01:41:26
	 */
	public Condition put(String columnName,Object value) {
		Condition condition = new Condition(columnName,value);
		coList.add(condition);
		return condition;
	}
	/**
	 * 存放在 特殊条件处  无值 比如 is not null
	 * TODO  
	 * @author ouyang 创建时间：2012-03-12 01:41:26
	 */
	public Condition put(String columnName) {
		Condition condition = new Condition(columnName,"");
		coList.add(condition);
		return condition;
	}
	/**
	 * 自动组装 sql
	 * 返回结果自动在 sql语句前加入了 “ AND ”
	 */
	@Deprecated
	public String getWhereSQL() {
		init();
		return rsSqlString;
	}
	/**
	 * 自动组装 sql 
	 * String sourceSql 自定义的sql语句，即前半部分(不需要考虑是否有 where ，and 等 关键字)
	 */
	public String getSQL(String sourceSql) {
		init();
		String sql= rsSqlString;
		if(sql!=null && sql.length()>1){
			if(sourceSql.toLowerCase().contains("where")){
				if(sourceSql.toLowerCase().endsWith("where") || sourceSql.toLowerCase().endsWith("where ")){
					sql = 	sourceSql +" "+removeAndStr(sql);
				}else{
					sql = 	sourceSql +" "+sql;
				}
			}else{
				sql = 	sourceSql +" WHERE "+removeAndStr(sql);
			}
		}else{
			sql= sourceSql;
		}
		if(StringUtils.isNotEmpty(this.groupByString)){
			sql = sql + " GROUP BY "+groupByString;
		}
		if(orderByString!=null && orderByString.length()>0){ // add order by String
			 if(orderByString.contains(",")){ // judg is contains many items
				 String str = "";
				 String orderString="";
				 for (int i = 0; i < orderByString.split(",").length; i++) {
					 str = orderByString.split(",")[i];
					    if(str.contains("=")){
					    	orderString = orderString + " "+str.split("=")[0]+" "+str.split("=")[1]+"," ;
						}else {
							orderString = orderString + " "+str+"," ;
						}
				 }
				 sql = sql + orderString.substring(0, orderString.length()-1) ; // 去掉最后的 逗号
			 }else{//单个排序项
				if(orderByString.contains("=")){
					sql = sql + " ORDER BY "+orderByString.split("=")[0]+" "+orderByString.split("=")[1] ;
				}else {
					sql = sql + " ORDER BY "+orderByString ;
				}
			 }
		}
		return sql;
	}
    /**
     * 返回参数
     */
	public List<Object> getParamList() {
		init();
		return paramList;
	}

	public List<Condition> getCoList() {
		return coList;
	}
	
	private String removeAndStr (String sql) {
		if(sql!=null && sql.length()>4 && sql.startsWith(" AND")){
			return sql.substring(4, sql.length());
		}
		return sql;
	}
	/**
	 * 初始化 排序  
	 *  多个指定排序：query.orderBy('GAME_ID=ASC,GAME_NAME=DESC');
	 *  多个混合排序：query.orderBy('GAME_ID,GAME_CODE,GAME_NAME=DESC');
	 *  单个默认升序：query.orderBy('ORDER_NUM');
	 *  单个指定排序：query.orderBy('ORDER_NUM=DESC');
	 * 注意：不需要带 order By
	 * @author ouyang 创建时间：Apr 12, 2012 5:01:59 PM
	 */
	public void orderBy(String str) {
		if (str!=null && str.length()>0) {
			orderByString = str;
		}
	}
	// 分组查询
	public void groupBy(String str) {
		if (str!=null && str.length()>0) {
			groupByString = str;
		}
	}
	
	public Object getParam(String paramKey) {
		if(paramKey != null && paramKey.length() > 0 && coList != null && coList.size() > 0) {
			for (Condition condition : coList) {
				if(paramKey.equals(condition.getColumnName())) {
					return condition.getValue();
				}
			}
		}
		return paramMap.get(paramKey);
	}
	
	public Map<String, Object> getParamMap() {
		return paramMap;
	}
}  
